class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int n = matrix.size();
        int m = matrix[0].size();
        int i = 0, j = m - 1;
        while (i < n && j >= 0) {
            int x = matrix[i][j];
            if (x < target) {
                i++;
            }
            else if (x > target) {
                j--;
            }
            else return 1;
        }
        return 0;
    }
};